﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace ManagoMes.Read.API.Applications.SellStockSearchRead
{
    public class SellStockSearchHandler : IRequestHandler<SellStockSearchCommand, PageDTO<SellStockDTO>>
    {
        private readonly IBateRepository<SellStockDTO> _sellStockRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sellStockRepository"></param>
        public SellStockSearchHandler(IBateRepository<SellStockDTO> sellStockRepository)
        {
            _sellStockRepository = sellStockRepository;
        }
        /// <summary>
        /// 销售出库显示+分页+条件查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<PageDTO<SellStockDTO>> Handle(SellStockSearchCommand request, CancellationToken cancellationToken)
        {
            //连接数据库
            DapperHelper dapper = new DapperHelper();
            string conn = dapper.MangoMesRead;
            //分页查询
            PageDTO<SellStockDTO> str = new PageDTO<SellStockDTO>();
            var pageNum = (request.pageIndex-1)*request.pageSize;
            //实体DTO
            SellStockDTO ssk = new SellStockDTO();
            string sql = "select * from sellStock inner join clientmanagement " +
                "on sellstock.ClientId=clientmanagement.ClientId where sellstock.SellStockState=0";
            var result = _sellStockRepository.GetAll(sql, ssk, conn).ToList();
            if (!string.IsNullOrEmpty(request.SellStockNo)){
                result = result.Where(p => p.SellStockNo == request.SellStockNo).ToList();
            }
            if (!string.IsNullOrEmpty(request.SellStockIndent))
            {
                result = result.Where(p => p.SellStockIndent == request.SellStockIndent).ToList();
            }
            if (!string.IsNullOrEmpty(request.ClientName))
            {
                result = result.Where(p => p.ClientName.Contains(request.ClientName)).ToList();
            }
            if(request.SellStockTime != null)
            {
                result = result.Where(p => p.SellStockTime.ToString("yyyy-MM-dd") == request.SellStockTime.Value.ToString("yyyy-MM-dd")).ToList();
            }
            if(request.SellStockStart > -1)
            {
                result = result.Where(p => p.SellStockStart == request.SellStockStart).ToList();
            }
            str.TotalCount = result.Count();
            str.PageCount = (int)Math.Ceiling((result.Count() * 1.0) / request.pageSize);
            result = result.OrderBy(p=>p.SellStockId).Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            str.Data = result;
            return str;
        }
    }
}
